package jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author azzhu
 * @create 2020-03-30 16:24:17
 */
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcApp {

    @Value("${prop.driverClass}")
    private String driverClass;

    @Value("${prop.userName}")
    private String user;

    @Value("${prop.url}")
    private String jdbcUrl;

    @Value("${prop.password}")
    private String passwd;

    @Bean
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        //为DataSource的属性赋值
        dataSource.setUser(user);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setDriverClass(driverClass);
        dataSource.setPassword(passwd);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(getDataSource());
        return jdbcTemplate;
    }
}
